package com.hw.blog.utils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.apache.log4j.Logger;

public class MailUtil {

	Logger log = Logger.getLogger(getClass());

	/**
	 * @param args
	 * @throws UnsupportedEncodingException
	 */
	public static void main(String[] args) throws UnsupportedEncodingException {
		// TODO Auto-generated method stub
		try {
			String[] emailList = { "chejug@gmail.com" };// 메일 보낼사람 리스트 
			String emailFromAddress = "chejug@gmail.com";// 메일 보내는 사람
			String emailMsgTxt = "메일 테스트 내용 "; // 내용
			String emailSubjectTxt = "잘가는지 테스트 중~~~~~~~~~~";// 제목
			MailUtil  nMail = new MailUtil();
			// 메일보내기 
			nMail.postMail(emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
//			System.out.println("모든 사용자에게 메일이 성공적으로 보내졌음~~");
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		
		
//
//		String sTitle = "김형욱 테스트";
//		String sContents = "This is a message body.\nHere's the second line. 한글포함";
//		// 아래 인코딩 부분은 환경에 따라 제목의 한글이 깨질 경우 주석을 제거하세요.
//		sTitle = new String(sTitle.getBytes("euc-kr"), "8859_1");
//
//		String to = "chejug@gmail.com";
//		String from = "chejug@naver.com";
//		String host = ConstValue.MAIL_SERVER_HOST;
//
//		// create some properties and get the default Session
//		Properties props = new Properties();
//		props.put("mail.smtp.host", host);
//
//		Session sess = Session.getDefaultInstance(props, null);
//
//		try {
//			// create a message
//			Message msg = new MimeMessage(sess);
//			msg.setFrom(new InternetAddress(from));
//			InternetAddress[] address = { new InternetAddress(to) };
//			msg.setRecipients(Message.RecipientType.TO, address);
//			msg.setSubject(sTitle);
//			msg.setSentDate(new Date());
//			msg.setContent(sContents + host, "text/html; charset=euc-kr"); // HTML
//																			// 형식
//			// msg.setText(sContents); // TEXT 형식
//
//			Transport.send(msg);
//			System.out.println("전송 완료");
//		} catch (MessagingException mex) {
//
//			// log.error("error : ");
//
//			System.out.println(mex.toString());
//
//		}
	}

	public String sendMail(String title, String content, String toEamil,
			String fromEail) {
		String sTitle = "";
		try {
			sTitle = MimeUtility.encodeText(title, "KSC5601", "B");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String to = toEamil;
		String from = fromEail;
		String host =ConstValue.MAIL_SERVER_HOST;

		// create some properties and get the default Session
		Properties props = new Properties();
		props.put("mail.smtp.host", host);

		Session sess = Session.getDefaultInstance(props, null);

		try {
			// create a message
			Message msg = new MimeMessage(sess);
			msg.setFrom(new InternetAddress(from));
			InternetAddress[] address = { new InternetAddress(to) };
			msg.setRecipients(Message.RecipientType.TO, address);
			msg.setSubject(sTitle);
			msg.setSentDate(new Date());
			// msg.setContent(sContents + host, "text/html; charset=euc-kr"); //
			// HTML
			msg.setContent(content, "text/html; charset=euc-kr"); // HTML
																	// 형식
			// msg.setText(sContents); // TEXT 형식

			Transport.send(msg);
			return "0000";
		} catch (MessagingException mex) {
			log.info(mex.toString());
			return "0001";
		}

	}
	
	
		boolean debug = false;
		public void postMail(String recipients[], String subject, String message, String from) throws MessagingException {
		java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
 
		String SMTP_HOST_NAME = "gmail-smtp.l.google.com";
		
		// Properties 설정
		Properties props = new Properties();
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.starttls.enable","true");
		props.put("mail.smtp.host", SMTP_HOST_NAME);
		props.put("mail.smtp.auth", "true");
 
		Authenticator auth = new SMTPAuthenticator();
		Session session = Session.getDefaultInstance(props, auth);
 
		session.setDebug(debug);
 
		// create a message
		Message msg = new MimeMessage(session);
 
		// set the from and to address
		InternetAddress addressFrom = new InternetAddress(from);
		msg.setFrom(addressFrom);
 
		InternetAddress[] addressTo = new InternetAddress[recipients.length];
		for (int i = 0; i < recipients.length; i++) {
			addressTo[i] = new InternetAddress(recipients[i]);
		}
		msg.setRecipients(Message.RecipientType.TO, addressTo);
 
		// Setting the Subject and Content Type
		msg.setSubject(subject);
		msg.setContent(message, "text/plain");
		Transport.send(msg);
	}
 
	/**
	 * 구글 사용자 메일 계정 아이디/패스 정보
	 */
	private class SMTPAuthenticator extends javax.mail.Authenticator {
		public PasswordAuthentication getPasswordAuthentication() {
			String username =  "chejug@gmail.com"; // gmail 사용자;
			String password = "khw460517"; // 패스워드;
			return new PasswordAuthentication(username, password);
		}
	}

}
